<template>
	<view class="container">
		<!-- 1. 黄金三秒，锁定眼球 -->
		<view class="hero-section">
			<image class="hero-image" src="/static/images/hero-bg.png" mode="widthFix"></image>
			<view class="hero-content">
				<view class="nav-links">
					<text @click="goToDistributionCenter">我的分销</text>
				</view>
				<text class="main-title">AI智能童伴学习机</text>
				<text class="sub-title">能聊会教的AI伙伴 + 价值千元的家庭福利</text>
				<text class="sub-title">能聊会教的AI伙伴 + 价值千元的家庭福利</text>
				<view class="price-section">
					<text class="promo-price">限时补贴价 ¥299</text>
					<text class="original-price">原价 ¥499</text>
				</view>
				<view class="gift-banner">
					<text>立即抢购，即赠价值2226元鄂尔多斯全年畅游卡！</text>
				</view>
				<view class="countdown">
					<text>限时抢购 | 剩 {{ hours }} : {{ minutes }} : {{ seconds }}</text>
				</view>
				<button class="cta-button" @click="scrollToPurchase">立即抢购</button>
			</view>
		</view>

		<!-- 2. 击中痛点，引发共鸣 -->
		<view class="pain-points-section">
			<view class="section-title">
				<text>您是否也有这样的育儿烦恼？</text>
			</view>
			<view class="points-grid">
				<view class="point-item" v-for="(point, index) in painPoints" :key="index">
					<image class="point-icon" :src="point.icon" mode="aspectFit"></image>
					<text class="point-text">{{ point.text }}</text>
				</view>
			</view>
		</view>

		<!-- 3. 展示方案，AI智能童伴如何解决一切 -->
		<view class="features-section">
			<view class="section-title">
				<text>一台AI智能童伴，就是孩子的全能成长伙伴</text>
			</view>
			<view class="feature-item" v-for="(feature, index) in features" :key="index">
				<image class="feature-gif" :src="feature.gif" mode="widthFix"></image>
				<view class="feature-content">
					<text class="feature-title">{{ feature.title }}</text>
					<text class="feature-description">{{ feature.description }}</text>
				</view>
			</view>
		</view>

		<!-- 4. 引爆价值，超值赠品详细介绍 -->
		<view class="gift-section">
			<view class="section-title">
				<text>惊喜不止于此！下单即赠【鄂尔多斯旅游一卡通】</text>
			</view>
			<view class="gift-card">
				<image class="gift-card-image" src="/static/images/travel-card.png" mode="widthFix"></image>
				<view class="gift-value">
					<text class="value-text">政府补贴，真实价值</text>
					<text class="value-amount">¥2226</text>
				</view>
			</view>
			<view class="gift-details">
				<text class="detail-highlight">全年365天、不限次数、免费畅玩！</text>
				<text class="detail-sub">鄂尔多斯数十家核心景区</text>
			</view>
			<view class="scenic-spots">
				<view class="spot-item" v-for="(spot, index) in scenicSpots" :key="index">
					<image class="spot-image" :src="spot.image" mode="aspectFill"></image>
					<text class="spot-name">{{ spot.name }}</text>
					<text class="spot-price">原价¥{{ spot.price }}</text>
				</view>
			</view>
			<view class="trust-badge">
				<text>鄂尔多斯文旅局监制</text>
			</view>
		</view>

		<!-- 5. 价值对比，让用户感觉占了大便宜 -->
		<view class="value-comparison-section" id="purchase-section">
			<view class="section-title">
				<text>今天下单，您将获得什么？</text>
			</view>
			<view class="value-box">
				<view class="value-item">
					<text class="item-name">AI智能童伴学习机</text>
					<text class="item-price">市场价 ¥499</text>
				</view>
				<view class="value-item">
					<text class="item-name">鄂尔多斯旅游一卡通</text>
					<text class="item-price">官方价值 ¥2226</text>
				</view>
				<view class="value-total">
					<text class="total-label">总价值</text>
					<text class="total-strikethrough">¥2725</text>
				</view>
				<view class="final-price">
					<text class="final-label">今日特惠价</text>
					<text class="price-highlight">仅需 ¥299</text>
				</view>
				<view class="savings">
					<text class="savings-text">您立省 ¥2426！</text>
				</view>
			</view>
		</view>
		
		<!-- 6. 信任背书，打消最后顾虑 -->
		<view class="trust-section">
			<view class="section-title">
				<text>权威认证 · 用户好评</text>
			</view>
			<!-- 用户评价轮播 -->
			<view class="testimonial-slider">
				<swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500">
					<swiper-item v-for="(testimonial, index) in testimonials" :key="index">
						<view class="testimonial-item">
							<image class="avatar" :src="testimonial.avatar"></image>
							<view class="testimonial-content">
								<text class="name">{{ testimonial.name }}</text>
								<text class="comment">"{{ testimonial.comment }}"</text>
							</view>
						</view>
					</swiper-item>
				</swiper>
			</view>
			<!-- 权威认证 -->
			<view class="certifications">
				<view class="cert-item" v-for="(cert, index) in certifications" :key="index">
					<image class="cert-icon" :src="cert.icon"></image>
					<text class="cert-text">{{ cert.text }}</text>
				</view>
			</view>
			<!-- 服务承诺 -->
			<view class="promises">
				<view class="promise-item" v-for="(promise, index) in promises" :key="index">
					<image class="promise-icon" :src="promise.icon"></image>
					<text>{{ promise.text }}</text>
				</view>
			</view>
		</view>

		<!-- 7. 行动号召与购买/分销入口 -->
		<view class="purchase-footer">
			<view class="footer-content">
				<view class="price-info">
					<text class="footer-price">合计：<text class="price-highlight">¥299</text></text>
					<text class="savings-info">立省¥2426</text>
				</view>
				<button class="purchase-button" @click="handlePurchase">立即支付</button>
			</view>
			<view class="distribution-info">
				<text>成功购买后将自动获得分销资格，分享赚取高额返利！</text>
			</view>
			<view class="payment-methods">
				<image class="payment-icon" src="/static/images/wechat-pay.png"></image>
				<image class="payment-icon" src="/static/images/alipay.png"></image>
			</view>
		</view>

		<!-- 支付成功弹窗 -->
		<uni-popup ref="successPopup" type="center">
			<view class="success-popup">
				<image class="success-icon" src="/static/images/success.png"></image>
				<text class="success-title">支付成功！</text>
				<text class="success-desc">恭喜您获得分销资格，分享给好友即可赚取佣金！</text>
				<view class="success-buttons">
					<button class="success-btn" @click="goToDistributionCenter">去分销中心</button>
					<button class="success-btn outline" @click="closeSuccessPopup">继续浏览</button>
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				hours: '23',
				minutes: '59',
				seconds: '59',
				painPoints: [{
						icon: '/static/images/icon-why.png',
						text: '孩子总问为什么 我却答不上来'
					},
					{
						icon: '/static/images/icon-busy.png',
						text: '工作太忙没时间 心怀愧疚'
					},
					{
						icon: '/static/images/icon-english.png',
						text: '英语启蒙难 发音不准不敢说'
					},
					{
						icon: '/static/images/icon-phone.png',
						text: '沉迷手机电视 不爱交流'
					},
					{
						icon: '/static/images/icon-homework.png',
						text: '辅导作业鸡飞狗跳 亲子关系紧张'
					}
				],
				features: [{
						gif: '/static/images/feature-qa.gif',
						title: '全科知识问答',
						description: '内置DeepSeek、豆包等顶尖大模型，孩子的"十万个为什么"，它都懂。天文地理、历史人文，张口就问，即刻回答。'
					},
					{
						gif: '/static/images/feature-english.gif',
						title: '沉浸式英语陪练',
						description: '标准美式发音，支持实时纠错。从单词到对话，为孩子创造纯正语言环境，自信说出口。'
					},
					{
						gif: '/static/images/feature-writing.gif',
						title: '高级写作指导',
						description: '从看图写话到构思作文，AI辅助孩子打开思路，学习修辞手法，提升表达能力。'
					},
					{
						gif: '/static/images/feature-emotion.gif',
						title: '情绪安抚与聊天',
						description: '化身贴心"小树洞"，倾听孩子心事，用积极正向的语言进行情绪疏导，培养健康心态。'
					},
					{
						gif: '/static/images/feature-resource.gif',
						title: '海量学习资源',
						description: '内置国学经典、成语故事、晚安童话等海量资源，随时随地磨耳朵。'
					}
				],
				scenicSpots: [
					{ 
						image: '/static/images/spot1.png',
						name: '响沙湾',
						price: '280'
					},
					{ 
						image: '/static/images/spot2.png',
						name: '成吉思汗陵',
						price: '180'
					},
					{ 
						image: '/static/images/spot3.png',
						name: '鄂尔多斯草原',
						price: '150'
					},
					{ 
						image: '/static/images/spot4.png',
						name: '康巴什新区',
						price: '120'
					}
				],
				testimonials: [
					{
						avatar: '/static/images/avatar1.png',
						name: '小明妈妈',
						comment: '太值了！孩子很喜欢这个机器人，每天都要跟它聊半天，旅游卡也真实有效，准备暑假就去鄂尔多斯玩！'
					},
					{
						avatar: '/static/images/avatar2.png',
						name: '乐乐爸爸',
						comment: '功能很强大，问什么都能答上来，英语发音比我都标准，解决了我的大难题。'
					},
					{
						avatar: '/static/images/avatar3.png',
						name: '小美妈妈',
						comment: '299元买到这么智能的伙伴，还送旅游卡，真的是赚到了！孩子现在学习兴趣提高了不少。'
					}
				],
				certifications: [
					{ icon: '/static/images/cert-3c.png', text: '3C认证' },
					{ icon: '/static/images/cert-deepseek.png', text: 'DeepSeek技术' },
					{ icon: '/static/images/cert-doubao.png', text: '豆包AI支持' }
				],
				promises: [
					{ icon: '/static/images/icon-auth.png', text: '正品保障' },
					{ icon: '/static/images/icon-return.png', text: '7天无理由' },
					{ icon: '/static/images/icon-warranty.png', text: '一年质保' },
					{ icon: '/static/images/icon-cs.png', text: '在线客服' },
				]
			}
		},
		onLoad(options) {
			// 预加载JS-SDK，确保支付时可用
			this.preloadWxSDK();
			// 解析 URL query 参数，兼容微信授权回调
			const urlParams = new URLSearchParams(window.location.search);
			if (urlParams.has('code')) {
				options.code = urlParams.get('code');
			}
			if (urlParams.has('state')) {
				options.state = urlParams.get('state');
			}

			console.log('页面加载，URL参数:', options);

			if (!this.isWeixin()) {
				uni.showModal({
					title: '提示',
					content: '请用微信扫码打开本页面',
					showCancel: false
				});
				return;
			}

			// 优先使用localStorage，兼容uniapp和原生H5
			let token = localStorage.getItem('user_token');
			if (!token) {
				token = uni.getStorageSync('user_token');
			}
			
			if (options.code) {
				console.log('检测到code，执行登录流程');
				this.handleLogin(options.code, options.state);
			} 
			else if (!token) {
				console.log('没有token且没有code，准备跳转到微信授权');
				const inviterCode = options.ref || null; // 获取可能存在的邀请码
				this.redirectToAuth(inviterCode);
			} else {
				console.log('已登录，token:', token);
				// 验证token是否有效
				this.validateToken(token);
			}
			
			// 启动倒计时
			this.startCountdown();

			// 检查登录状态
			this.checkLoginStatus();
			
			// 调试信息：显示当前URL信息
			console.log('=== URL调试信息 ===');
			console.log('完整URL:', window.location.href);
			console.log('协议:', window.location.protocol);
			console.log('主机:', window.location.host);
			console.log('路径:', window.location.pathname);
			console.log('查询参数:', window.location.search);
			console.log('Hash:', window.location.hash);
			console.log('去除Hash后的URL:', window.location.href.split('#')[0]);
			console.log('==================');

			this.autoLoginByCode();
		},
		computed: {
		},
		methods: {
			isWeixin() {
				return /micromessenger/i.test(window.navigator.userAgent);
			},
			// 跳转到微信授权页
			redirectToAuth(inviterCode) {
				const backendApiBaseUrl = 'https://ai.huixinqi.cn';
				let authUrlEndpoint = `${backendApiBaseUrl}/app/aihaowu/user/get_auth_url?redirect=${encodeURIComponent(window.location.href)}`;
				if(inviterCode) {
					authUrlEndpoint += `&ref=${inviterCode}`;
				}
				uni.request({
					url: authUrlEndpoint,
					method: 'GET',
					success: (res) => {
						if(res.data.code === 0 && res.data.data.auth_url) {
							console.log('成功获取到授权URL:', res.data.data.auth_url);
							window.location.href = res.data.data.auth_url;
						} else {
							uni.showToast({ title: '获取授权地址失败', icon: 'none'});
						}
					},
					fail: () => {
						uni.showToast({ title: '请求授权地址失败', icon: 'none'});
					}
				});
			},

			// 执行登录
			handleLogin(code, state) {
				const backendApiBaseUrl = 'https://ai.huixinqi.cn';
				const loginUrl = `${backendApiBaseUrl}/app/aihaowu/user/login`;

				uni.request({
					url: loginUrl,
					method: 'POST',
					data: {
						code: code,
						state: state
					},
					success: (res) => {
						if (res.data.code === 0 && res.data.data.token) {
							// 同时存储到localStorage和uni.storage，确保兼容性
							localStorage.setItem('user_token', res.data.data.token);
							uni.setStorageSync('user_token', res.data.data.token);
							console.log('后端登录成功，token已保存');

							// 登录成功后，跳转到无 code/state 的原始页面，彻底清理参数
							const cleanUrl = window.location.origin + window.location.pathname + window.location.hash;
							window.location.replace(cleanUrl);
						} else {
							uni.showToast({
								title: `登录失败: ${res.data.msg}`,
								icon: 'none'
							});
							console.error('后端登录失败', res);
						}
					},
					fail: (err) => {
						uni.showToast({ title: '登录请求异常', icon: 'none' });
						console.error('登录请求失败', err);
					}
				});
			},
			startCountdown() {
				let endTime = new Date();
				endTime.setHours(endTime.getHours() + 24);

				setInterval(() => {
					let now = new Date();
					let remaining = endTime - now;

					if (remaining > 0) {
						this.hours = String(Math.floor((remaining / (1000 * 60 * 60)) % 24)).padStart(2, '0');
						this.minutes = String(Math.floor((remaining / 1000 / 60) % 60)).padStart(2, '0');
						this.seconds = String(Math.floor((remaining / 1000) % 60)).padStart(2, '0');
					} else {
						this.hours = '00';
						this.minutes = '00';
						this.seconds = '00';
					}
				}, 1000);
			},
			scrollToPurchase(){
				uni.pageScrollTo({
					selector: '#purchase-section',
					duration: 300
				});
			},
			goToDistributionCenter() {
				uni.navigateTo({
					url: '/pages/distribution/center'
				});
			},
			handlePurchase() {
				console.log('开始处理支付请求...');
				// 优先使用localStorage，兼容uniapp和原生H5
				let token = localStorage.getItem('user_token');
				if (!token) {
					token = uni.getStorageSync('user_token');
				}
				console.log('获取到的token:', token ? '存在' : '不存在');
				if (!token) {
					uni.showToast({ title: '请先登录', icon: 'none' });
					return;
				}
				console.log('开始创建订单...');
				uni.showLoading({ title: '正在创建订单...' });
				const backendApiBaseUrl = 'https://ai.huixinqi.cn';
				const createOrderUrl = `${backendApiBaseUrl}/app/aihaowu/order/create`;
				uni.request({
					url: createOrderUrl,
					method: 'POST',
					header: { 'Authorization': `Bearer ${token}` },
					success: (res) => {
						uni.hideLoading();
						if (res.data.code === 0) {
							console.log('订单创建成功，准备支付', res.data);
							const paymentParams = res.data.data.pay_params; // 正确
							if (!paymentParams) {
								uni.showToast({ title: '支付参数异常', icon: 'none' });
								return;
							}
							this.requestWxPayment(paymentParams);
						} else {
							console.error('创建订单失败', res.data);
							uni.showToast({ title: res.data.msg || '创建订单失败', icon: 'none' });
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('请求失败', err);
						uni.showToast({ title: '网络请求失败，请重试', icon: 'none' });
					}
				});
			},
			// 实际调用微信支付
			requestWxPayment(params) {
				// 在H5环境下，使用微信JS-SDK调起支付
				if (this.isWeixin()) {
					this.callWechatPayWithSDK(params);
				} else {
					console.log('非微信环境，使用uni.requestPayment', res);
					// 非微信环境，使用uni.requestPayment
					uni.requestPayment({
						provider: 'wxpay',
						...params,
						success: (res) => {
							console.log('支付成功', res);
							// 显示支付成功弹窗
							this.$refs.successPopup.open();
						},
						fail: (err) => {
							console.log('支付失败', err);
							uni.showToast({ title: '支付已取消', icon: 'none' });
						}
					});
				}
			},
			
			// 使用微信JS-SDK调起支付
			async callWechatPayWithSDK(payParams) {
				try {
					console.log('开始调起微信支付，参数:', payParams);
					
					// 等待JS-SDK加载，简化版本（因为已在index.html中同步加载）
					await this.waitForWxSDK();
					
					// 再次检查wx对象是否真正可用
					if (!window.wx) {
						console.warn('JS-SDK加载失败，wx对象不可用，尝试直接调用支付');
						// 尝试直接调用支付，可能JS-SDK已经加载但检测不到
						this.callWxPayDirectly(payParams);
						return;
					}
					
					console.log('JS-SDK加载完成，wx对象:', window.wx);
					console.log('wx.config是否存在:', typeof window.wx.config);
					console.log('wx.ready是否存在:', typeof window.wx.ready);
					console.log('wx.chooseWXPay是否存在:', typeof window.wx.chooseWXPay);
					
					const jsConfig = await this.getJsConfig();
					console.log('获取到JS-SDK配置:', jsConfig);
					console.log('准备调用 wx.config', jsConfig);
					
					// 检查wx.config是否可用，如果不可用则尝试直接调用支付
					if (typeof window.wx.config !== 'function') {
						console.warn('wx.config不可用，尝试直接调用支付');
						// 直接尝试调用支付，跳过config步骤
						this.callWxPayDirectly(payParams);
						return;
					}
					
					// 设置config超时处理
					const configTimeout = setTimeout(() => {
						console.warn('wx.config超时，尝试直接调用支付');
						this.callWxPayDirectly(payParams);
					}, 5000);
					
					window.wx.config({
						debug: false, // 生产环境关闭debug
						appId: jsConfig.appId,
						timestamp: jsConfig.timestamp,
						nonceStr: jsConfig.nonceStr,
						signature: jsConfig.signature,
						jsApiList: ['chooseWXPay']
					});
					console.log('wx.config 已调用');
					
					window.wx.ready(() => {
						clearTimeout(configTimeout);
						console.log('wx.ready 回调触发');
						window.wx.chooseWXPay({
							timestamp: payParams.timeStamp,
							nonceStr: payParams.nonceStr,
							package: payParams.package,
							signType: payParams.signType,
							paySign: payParams.paySign,
							success: (res) => {
								console.log('支付成功', res);
								this.$refs.successPopup.open();
							},
							cancel: (res) => {
								console.log('支付已取消', res);
								uni.showToast({ title: '支付已取消', icon: 'none' });
							},
							fail: (res) => {
								console.log('支付失败', res);
								uni.showToast({ title: '支付失败: ' + (res.errMsg || '未知错误'), icon: 'none' });
							}
						});
						console.log('wx.chooseWXPay 调用');
					});
					
					window.wx.error((res) => {
						clearTimeout(configTimeout);
						console.log('wx.error', res);
						console.warn('wx.config失败，尝试直接调用支付');
						// config失败时也尝试直接调用支付
						this.callWxPayDirectly(payParams);
					});
				} catch (error) {
					console.error('调起支付失败', error);
					// 即使出错也尝试直接调用支付
					console.warn('尝试直接调用支付作为备用方案');
					this.callWxPayDirectly(payParams);
				}
			},
			
			// 直接调用微信支付，跳过config步骤
			callWxPayDirectly(payParams) {
				try {
					console.log('尝试直接调用微信支付');
					
					// 检查chooseWXPay是否可用
					if (!window.wx) {
						console.error('window.wx不存在，无法调用支付');
						uni.showToast({ title: '微信支付不可用，请刷新页面重试', icon: 'none' });
						return;
					}
					
					if (typeof window.wx.chooseWXPay !== 'function') {
						console.error('wx.chooseWXPay方法不可用');
						uni.showToast({ title: '微信支付方法不可用，请刷新页面重试', icon: 'none' });
						return;
					}
					
					console.log('开始调用wx.chooseWXPay，参数:', payParams);
					
					window.wx.chooseWXPay({
						timestamp: payParams.timeStamp,
						nonceStr: payParams.nonceStr,
						package: payParams.package,
						signType: payParams.signType,
						paySign: payParams.paySign,
						success: (res) => {
							console.log('支付成功', res);
							this.$refs.successPopup.open();
						},
						cancel: (res) => {
							console.log('支付已取消', res);
							uni.showToast({ title: '支付已取消', icon: 'none' });
						},
						fail: (res) => {
							console.log('支付失败', res);
							uni.showToast({ title: '支付失败: ' + (res.errMsg || '未知错误'), icon: 'none' });
						}
					});
					console.log('直接调用wx.chooseWXPay成功');
				} catch (error) {
					console.error('直接调用支付失败', error);
					uni.showToast({ title: '支付调用失败: ' + error.message, icon: 'none' });
				}
			},
			
			// 等待JS-SDK加载，简化版本（因为已在index.html中同步加载）
			waitForWxSDK() {
				return new Promise((resolve, reject) => {
					let attempts = 0;
					const maxAttempts = 20; // 最多等待1秒
					
					const check = () => {
						attempts++;
						console.log(`JS-SDK检查第${attempts}次, window.wx:`, window.wx);
						
						// 检查wx对象和方法是否可用
						if (window.wx && typeof window.wx.config === 'function' && typeof window.wx.chooseWXPay === 'function') {
							console.log('JS-SDK加载成功，准备调用支付');
							resolve();
						} else if (attempts >= maxAttempts) {
							console.error('JS-SDK加载超时，尝试手动加载');
							// 超时后尝试手动加载JS-SDK
							this.loadWxSDKManually().then(() => {
								console.log('手动加载JS-SDK成功');
								resolve();
							}).catch((error) => {
								console.error('手动加载JS-SDK失败:', error);
								reject(new Error('JS-SDK加载失败，请刷新页面重试'));
							});
						} else {
							setTimeout(check, 50);
						}
					};
					check();
				});
			},
			
			// 手动加载JS-SDK作为备用方案
			loadWxSDKManually() {
				return new Promise((resolve, reject) => {
					// 检查是否已经存在
					if (window.wx) {
						resolve();
						return;
					}
					
					const script = document.createElement('script');
					script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
					
					const timeout = setTimeout(() => {
						reject(new Error('手动加载JS-SDK超时'));
					}, 8000); // 增加超时时间到8秒
					
					script.onload = () => {
						clearTimeout(timeout);
						// 给JS-SDK更多时间初始化，适应uniapp环境
						setTimeout(() => {
							if (window.wx) {
								console.log('手动加载JS-SDK成功');
								resolve();
							} else {
								console.warn('JS-SDK加载完成但window.wx未定义，尝试继续使用');
								// 即使window.wx未定义，也尝试继续，可能是uniapp环境问题
								resolve();
							}
						}, 2000); // 增加等待时间到2秒
					};
					
					script.onerror = () => {
						clearTimeout(timeout);
						reject(new Error('手动加载JS-SDK网络错误'));
					};
					
					document.head.appendChild(script);
				});
			},
			
			// 预加载JS-SDK，简化版本（因为已在index.html中同步加载）
			preloadWxSDK() {
				// 如果JS-SDK已经加载，直接返回
				if (window.wx && typeof window.wx.config === 'function') {
					console.log('JS-SDK已预加载完成');
					return;
				}
				
				console.log('JS-SDK未加载，等待index.html中的同步加载...');
				// 由于JS-SDK在index.html中同步加载，这里只需要等待即可
			},
			
			// 获取JS-SDK配置
			async getJsConfig() {
				// 优先使用localStorage，兼容uniapp和原生H5
				let token = localStorage.getItem('user_token');
				if (!token) {
					token = uni.getStorageSync('user_token');
				}
				
				if (!token) {
					throw new Error('用户未登录');
				}
				
				// 在hash模式下，需要去除hash部分用于JS-SDK签名
				// 确保URL格式正确，去除所有hash相关部分
				let currentUrl = window.location.href;
				if (currentUrl.includes('#')) {
					currentUrl = currentUrl.split('#')[0];
				}
				// 确保URL以/结尾（如果路径为空）
				if (currentUrl.endsWith('/h5') || currentUrl.endsWith('/h5/')) {
					currentUrl = currentUrl.replace(/\/h5\/?$/, '/h5/');
				}
				console.log('当前URL用于JS-SDK签名:', currentUrl);
				
				const response = await fetch(`https://ai.huixinqi.cn/app/aihaowu/order/js_config?url=${encodeURIComponent(currentUrl)}`, {
					headers: {
						'Authorization': `Bearer ${token}`
					}
				});
				
				const result = await response.json();
				if (result.code === 0) {
					return result.data;
				} else {
					throw new Error(result.msg || '获取JS-SDK配置失败');
				}
			},
			
			// 验证token是否有效
			async validateToken(token) {
				try {
					const response = await fetch('https://ai.huixinqi.cn/app/aihaowu/user/validate_token', {
						method: 'GET',
						headers: {
							'Authorization': `Bearer ${token}`
						}
					});
					
					const result = await response.json();
					if (result.code !== 0) {
						console.log('token无效，重新登录');
						// 同时清除localStorage和uni.storage
						localStorage.removeItem('user_token');
						uni.removeStorageSync('user_token');
						this.redirectToAuth();
					}
				} catch (error) {
					console.error('验证token失败', error);
					// 验证失败时，清除token并重新登录
					localStorage.removeItem('user_token');
					uni.removeStorageSync('user_token');
					this.redirectToAuth();
				}
			},
			closeSuccessPopup() {
				this.$refs.successPopup.close();
			},
			// 检查登录状态
			checkLoginStatus() {
				let token = localStorage.getItem('user_token');
				if (!token) {
					token = uni.getStorageSync('user_token');
				}
				if (!token) {
					this.redirectToAuth();
					return false;
				}
				// 可选：进一步校验token有效性
				this.validateToken(token);
				return true;
			},
			// 自动处理微信授权回调，自动登录
			autoLoginByCode() {
				const urlParams = new URLSearchParams(window.location.search);
				const code = urlParams.get('code');
				const state = urlParams.get('state');
				if (code) {
					const backendApiBaseUrl = 'https://ai.huixinqi.cn';
					const loginUrl = `${backendApiBaseUrl}/app/aihaowu/user/login`;
					uni.request({
						url: loginUrl,
						method: 'POST',
						data: { code, state },
						success: (res) => {
							if (res.data.code === 0 && res.data.data.token) {
								localStorage.setItem('user_token', res.data.data.token);
								uni.setStorageSync('user_token', res.data.data.token);
								// 清理URL参数，跳转到无code的原始页面
								const cleanUrl = window.location.origin + window.location.pathname + window.location.hash;
								window.location.replace(cleanUrl);
							} else {
								uni.showToast({ title: '自动登录失败', icon: 'none' });
							}
						},
						fail: (err) => {
							uni.showToast({ title: '自动登录异常', icon: 'none' });
						}
					});
				}
			},
			// 补全 callUniAppPay，避免报错
			callUniAppPay(payParams) {
				uni.showToast({ title: '请在微信内完成支付', icon: 'none' });
			},
		}
	}
</script>

<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
		padding-bottom: 180rpx; /* 为底部购买栏留出空间 */
	}

	.section-title {
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin: 40rpx 0;
		padding: 0 30rpx;
	}
	
	.price-highlight {
		color: #e53935;
		font-weight: bold;
	}

	/* 1. Hero Section */
	.hero-section {
		position: relative;
		width: 100%;
	}

	.nav-links {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		background-color: rgba(0,0,0,0.3);
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		color: white;
	}

	.hero-image {
		width: 100%;
		height: auto;
	}

	.hero-content {
		position: absolute;
		top: 50rpx;
		left: 0;
		width: 100%;
		text-align: center;
		color: white;
		display: flex;
		flex-direction: column;
		align-items: center;
		text-shadow: 0px 2px 4px rgba(0, 0, 0, 0.5);
	}
	
	.main-title {
		font-size: 52rpx;
		font-weight: bold;
	}
	
	.sub-title {
		font-size: 28rpx;
		margin-top: 10rpx;
		opacity: 0.9;
	}
	
	.price-section {
		display: flex;
		align-items: baseline;
		gap: 20rpx;
		margin-top: 20rpx;
		background-color: rgba(0,0,0,0.3);
		padding: 10rpx 20rpx;
		border-radius: 10rpx;
	}
	
	.promo-price {
		font-size: 40rpx;
		font-weight: bold;
		color: #ffd700;
	}
	
	.original-price {
		font-size: 28rpx;
		text-decoration: line-through;
	}

	.gift-banner {
		margin-top: 20rpx;
		background: linear-gradient(to right, #ff9a44, #ff5f6d);
		color: white;
		font-size: 28rpx;
		padding: 15rpx 30rpx;
		border-radius: 50rpx;
		box-shadow: 0 4rpx 10rpx rgba(0,0,0,0.2);
	}
	
	.countdown {
		margin-top: 20rpx;
		font-size: 32rpx;
		font-weight: bold;
		background-color: rgba(255, 255, 255, 0.9);
		color: #e53935;
		padding: 10rpx 30rpx;
		border-radius: 10rpx;
	}

	.cta-button {
		margin-top: 30rpx;
		background: linear-gradient(to right, #ff9a44, #ff5f6d);
		color: white;
		font-size: 36rpx;
		font-weight: bold;
		border: none;
		border-radius: 50rpx;
		padding: 20rpx 60rpx;
		box-shadow: 0 8rpx 15rpx rgba(0, 0, 0, 0.2);
	}
	
	/* 2. Pain Points Section */
	.pain-points-section {
		background-color: #ffffff;
		padding-bottom: 40rpx;
		border-radius: 20rpx;
		margin: 20rpx;
	}
	
	.points-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 40rpx;
		padding: 0 30rpx;
	}
	
	.point-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;
	}
	
	.point-icon {
		width: 100rpx;
		height: 100rpx;
		margin-bottom: 20rpx;
	}
	
	.point-text {
		font-size: 28rpx;
		color: #555;
	}
	
	/* 3. Features Section */
	.features-section {
		padding: 20rpx;
	}
	
	.feature-item {
		background-color: white;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
		overflow: hidden;
	}
	
	.feature-gif {
		width: 100%;
		height: auto;
	}
	
	.feature-content {
		padding: 30rpx;
	}
	
	.feature-title {
		font-size: 34rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}
	
	.feature-description {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
	}
	
	/* 4. Gift Section */
	.gift-section {
		background-color: white;
		padding: 40rpx 20rpx;
		margin: 20rpx;
		border-radius: 20rpx;
	}
	
	.gift-card {
		position: relative;
		margin-bottom: 30rpx;
	}
	
	.gift-card-image {
		width: 100%;
		height: auto;
		border-radius: 20rpx;
	}
	
	.gift-value {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		background: linear-gradient(to right, #ff9a44, #ff5f6d);
		color: white;
		padding: 15rpx 25rpx;
		border-radius: 15rpx;
		text-align: center;
	}
	
	.value-text {
		font-size: 24rpx;
		display: block;
	}
	
	.value-amount {
		font-size: 36rpx;
		font-weight: bold;
		display: block;
	}
	
	.gift-details {
		text-align: center;
		margin-bottom: 30rpx;
	}
	
	.detail-highlight {
		font-size: 32rpx;
		font-weight: bold;
		color: #e53935;
		display: block;
		margin-bottom: 10rpx;
	}
	
	.detail-sub {
		font-size: 28rpx;
		color: #666;
	}
	
	.scenic-spots {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}
	
	.spot-item {
		text-align: center;
	}
	
	.spot-image {
		width: 100%;
		height: 200rpx;
		border-radius: 15rpx;
		margin-bottom: 10rpx;
	}
	
	.spot-name {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		display: block;
	}
	
	.spot-price {
		font-size: 24rpx;
		color: #999;
	}
	
	.trust-badge {
		text-align: center;
		background-color: #f5f5f5;
		padding: 20rpx;
		border-radius: 15rpx;
		font-size: 28rpx;
		color: #666;
	}
	
	/* 5. Value Comparison Section */
	.value-comparison-section {
		background-color: white;
		padding: 40rpx 20rpx;
		margin: 20rpx;
		border-radius: 20rpx;
	}
	
	.value-box {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		padding: 40rpx;
		border-radius: 20rpx;
		color: white;
	}
	
	.value-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding: 15rpx 0;
		border-bottom: 1rpx solid rgba(255,255,255,0.2);
	}
	
	.item-name {
		font-size: 28rpx;
	}
	
	.item-price {
		font-size: 28rpx;
		font-weight: bold;
	}
	
	.value-total {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding: 15rpx 0;
		border-bottom: 2rpx solid rgba(255,255,255,0.3);
	}
	
	.total-label {
		font-size: 32rpx;
		font-weight: bold;
	}
	
	.total-strikethrough {
		font-size: 32rpx;
		font-weight: bold;
		text-decoration: line-through;
		opacity: 0.7;
	}
	
	.final-price {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding: 20rpx 0;
		border-bottom: 2rpx solid rgba(255,255,255,0.3);
	}
	
	.final-label {
		font-size: 36rpx;
		font-weight: bold;
	}
	
	.savings {
		text-align: center;
		padding: 20rpx 0;
	}
	
	.savings-text {
		font-size: 40rpx;
		font-weight: bold;
		color: #ffd700;
	}
	
	/* 6. Trust Section */
	.trust-section {
		background-color: white;
		padding: 40rpx 20rpx;
		margin: 20rpx;
		border-radius: 20rpx;
	}
	
	.testimonial-slider {
		margin-bottom: 40rpx;
	}
	
	.testimonial-item {
		display: flex;
		align-items: center;
		padding: 30rpx;
		background-color: #f8f9fa;
		border-radius: 15rpx;
		margin: 0 20rpx;
	}
	
	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}
	
	.testimonial-content {
		flex: 1;
	}
	
	.name {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}
	
	.comment {
		font-size: 26rpx;
		color: #666;
		line-height: 1.5;
	}
	
	.certifications {
		display: flex;
		justify-content: space-around;
		margin-bottom: 40rpx;
	}
	
	.cert-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.cert-icon {
		width: 80rpx;
		height: 80rpx;
		margin-bottom: 10rpx;
	}
	
	.cert-text {
		font-size: 24rpx;
		color: #666;
	}
	
	.promises {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 30rpx;
	}
	
	.promise-item {
		display: flex;
		align-items: center;
		background-color: #f8f9fa;
		padding: 20rpx;
		border-radius: 15rpx;
	}
	
	.promise-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 15rpx;
	}
	
	.promise-item text {
		font-size: 26rpx;
		color: #333;
	}
	
	/* 7. Purchase Footer */
	.purchase-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: white;
		padding: 20rpx;
		box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.1);
		z-index: 1000;
	}
	
	.footer-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 15rpx;
	}
	
	.price-info {
		display: flex;
		flex-direction: column;
	}
	
	.footer-price {
		font-size: 32rpx;
		color: #333;
	}
	
	.savings-info {
		font-size: 24rpx;
		color: #e53935;
	}
	
	.purchase-button {
		background: linear-gradient(to right, #ff9a44, #ff5f6d);
		color: white;
		font-size: 32rpx;
		font-weight: bold;
		border: none;
		border-radius: 50rpx;
		padding: 20rpx 40rpx;
	}
	
	.distribution-info {
		text-align: center;
		font-size: 24rpx;
		color: #666;
		margin-bottom: 10rpx;
	}
	
	.payment-methods {
		display: flex;
		justify-content: center;
		gap: 20rpx;
	}
	
	.payment-icon {
		width: 60rpx;
		height: 40rpx;
	}
	
	/* Success Popup */
	.success-popup {
		background-color: white;
		padding: 60rpx 40rpx;
		border-radius: 20rpx;
		text-align: center;
		width: 600rpx;
	}
	
	.success-icon {
		width: 120rpx;
		height: 120rpx;
		margin-bottom: 30rpx;
	}
	
	.success-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 20rpx;
	}
	
	.success-desc {
		font-size: 28rpx;
		color: #666;
		line-height: 1.5;
		margin-bottom: 40rpx;
	}
	
	.success-buttons {
		display: flex;
		gap: 20rpx;
	}
	
	.success-btn {
		flex: 1;
		padding: 20rpx;
		border-radius: 10rpx;
		font-size: 28rpx;
		border: none;
	}
	
	.success-btn:not(.outline) {
		background: linear-gradient(to right, #ff9a44, #ff5f6d);
		color: white;
	}
	
	.success-btn.outline {
		background-color: transparent;
		color: #666;
		border: 2rpx solid #ddd;
	}
</style>
